package com.kt.uokos.yimo.service.impl;

import com.github.pagehelper.PageHelper;
import com.kt.uokos.yimo.dao.CouponUser;
import com.kt.uokos.yimo.example.CouponUserExample;
import com.kt.uokos.yimo.mapper.CouponMapper;
import com.kt.uokos.yimo.mapper.CouponUserMapper;
import com.kt.uokos.yimo.service.CouponUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: TODO
 * @className: CouponUserServiceImpl.java
 * @author: Kang Hao
 * @date: 2022/4/26 15:14
 **/
@Service
public class CouponUserServiceImpl implements CouponUserService {

    @Resource
    private CouponUserMapper couponUserMapper;

    @Override
    public List<CouponUser> queryList(Integer userId, Integer couponId, Short status, Integer page, Integer size, String sort, String order) {
        CouponUserExample example = new CouponUserExample();
        CouponUserExample.Criteria criteria = example.createCriteria();

        if (userId != null){
            criteria.andUserIdEqualTo(userId);
        }

        if (couponId != null){
            criteria.andCouponIdEqualTo(couponId);
        }
        if (status != null){
            criteria.andStatusEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        if (!StringUtils.isEmpty(page) && !StringUtils.isEmpty(size)) {
            PageHelper.startPage(page, size);
        }

        return couponUserMapper.selectByExample(example);
    }

    @Override
    public Integer countUserAndCoupon(Integer userId, Integer couponId) {
        CouponUserExample example = new CouponUserExample();
        example.or().andUserIdEqualTo(userId).andCouponIdEqualTo(couponId).andDeletedEqualTo(false);
        return (int)couponUserMapper.countByExample(example);
    }

    @Override
    public void add(CouponUser couponUser) {
        couponUser.setAddTime(LocalDateTime.now());
        couponUser.setUpdateTime(LocalDateTime.now());
        couponUser.setDeleted(false);
        couponUser.setStatus((short)0);
        couponUserMapper.insert(couponUser);
    }
}
